package com.example.testJava.control;

import com.example.testJava.comm.AjaxResult;
import com.example.testJava.dao.Usertt;
import com.example.testJava.dao.UserttMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;

@Controller
public class Index {

    @Autowired
    UserttMapper userttMapper;
    /**
     * 查询项目列表
     */
    @GetMapping("/index")
    public String index(Model model) {
        model.addAttribute("var1", "王顺初");
//        String var1 = "王顺初";
        return "index";
    }

    @GetMapping("/list")
    public String list(Model model) {
        model.addAttribute("var1", "王顺初");
//        String var1 = "王顺初";
        return "/usertt/list";
    }

    @ResponseBody
    @PostMapping("get_users")
    public List getUsers() {
        List<Usertt> list1 = userttMapper.selectList(null);
        return list1;
    }

    @ResponseBody
    @PostMapping("save_user")
    public String saveUser(Usertt usertt) {
        try {
            int row = userttMapper.updateById(usertt);
            if (row == 1)
                return "ok";
            else
                return "error!";
        } catch (Exception ex) {
            return "error!";
        }
    }

    @ResponseBody
    @PostMapping("remove_user")
    public String removeUser(@RequestParam String id) {
        try {
            userttMapper.deleteById(id);
            return "ok";
        } catch (Exception ex) {
            return "error!";
        }
    }

    @ResponseBody
    @PostMapping("ajax")
    public AjaxResult removeUser() {
        System.out.println("I am here!");
        AjaxResult result = new AjaxResult();
        result.setMyCode(200);
        result.setMyMessage("this is a test");
        HashMap map = new HashMap<>();
        map.put(1, "wsc");
        map.put(2, "xhy");
        map.put(3, "wjy");
        map.put("This is ", "A Wonderful World");

        result.setMyData(map);
        return result;
    }

    @ResponseBody
    @PostMapping("upload")
    public AjaxResult upload(@RequestParam("file") MultipartFile file) throws IOException {
        file.transferTo(new File("c:\\wsc.tmp\\1" + file.getOriginalFilename()));
        AjaxResult result = new AjaxResult();
        result.setMyCode(200);
        return result;
    }

}
